import React from "react";
import NewBind from "./NewBind";
import RestNode from "./RestNode";
import Localhost from "./Localhost";
import { useState, useEffect } from "react";
const { Header, Content, Footer, Sider } = Layout;
import { Breadcrumb, Layout, Menu, theme, Button } from "antd";
import { postAllNodesList } from "@/services/nodes/api";
import {
    LaptopOutlined,
    NotificationOutlined,
    UserOutlined,
    PlusOutlined,
} from "@ant-design/icons";
import { useLocation, useNavigate } from "react-router-dom";
import NoFoundPage from "@/pages/404";

interface MenuItemType {
    key: string;
    label: string | (() => React.ReactNode);
    icon?: React.ReactNode;
    node_id: string;
    host: string;
    [propName: string]: any;
}

const Nodes: React.FC = () => {
    const [items, setItems] = useState<MenuItemType[]>([]);
    const [select, setSelect] = useState<string>("");
    const [selectNodeID, setSelectNodeID] = useState<string>("");
    const location = useLocation();
    const navigate = useNavigate();
    const initData = async (nodeId: string) => {
        await postAllNodesList(nodeId).then((res) => {
            const menuItems = res.message.map((item: any) => {
                const key = item.host === "localhost" ? "0" : item.node_id;
                if (item.host === "localhost") {
                    setSelectNodeID(item.node_id);
                }
                return {
                    key: key,
                    label: item.host === "localhost" ? "本机" : item.host,
                    icon: undefined,
                    node_id: item.node_id,
                    host: item.host,
                };
            });
            menuItems.push({
                key: "-1",
                // @ts-ignore
                icon: (
                    <div
                        style={{
                            display: "flex",
                            justifyContent: "center",
                            alignItems: "center",
                            width: "100%",
                        }}
                    >
                        <PlusOutlined />
                    </div>
                ),
                node_id: "-1",
                host: "add",
            });
            setItems(menuItems);
        });
    };

    useEffect(() => {
        const initNodeId = () => { 
            const param = new URLSearchParams(window.location.search);
            const temp_id = param.get("node_id")
            if (temp_id === null) {
                return "0";
            } else {
                return temp_id;
            }
        };
        initData(initNodeId());
        return () => {};
    }, []);

    useEffect(() => {
        const params = new URLSearchParams(location.search);
        const nodeId = params.get("node_id");
        if (!nodeId) {
            navigate("/nodes?node_id=0");
            return;
        }
        if (nodeId === "0") {
            setSelect("0");
            return;
        }
        if (nodeId === "-1") {
            setSelect("-1");
            return;
        }
        const node = items.find(
            (item: any) =>
                item.node_id === nodeId
        );
        if (node) {
            setSelect(node.key);
            setSelectNodeID(nodeId);
        } else {
            setSelect("-2");
        }
    }, [location.search, items]);

    // 定义返回本机节点的回调按钮组件
    const CallbackButton: React.FC = () => (
        <Button
            type="primary"
            onClick={() => {
                navigate("/nodes?node_id=0");
            }}
        >
            本机
        </Button>
    );

    const MainContent: React.FC = () => {
        if (select === "-1") {
            return (
                <Content
                    style={{
                        background: "#ffffff",
                        borderRadius: "8px",
                        boxShadow: "0 1px 1px rgba(0, 0, 0, 0.1)",
                        borderRight: "none",
                    }}
                >
                    <NewBind />
                </Content>
            );
        } else if (select === "0") {
            return (
                <Content
                    style={{
                        background: "#ffffff",
                        borderRadius: "8px",
                        boxShadow: "0 1px 1px rgba(0, 0, 0, 0.1)",
                        borderRight: "none",
                    }}
                >
                    <Localhost />
                </Content>
            );
        } else if (select === "-2") {
            return (
                <Content
                    style={{
                        background: "#ffffff",
                        borderRadius: "8px",
                        boxShadow: "0 1px 1px rgba(0, 0, 0, 0.1)",
                        borderRight: "none",
                    }}
                >
                    <NoFoundPage
                        title="节点不存在！"
                        CallbackButton={CallbackButton}
                    />
                </Content>
            );
        } else {
            return (
                <Content
                    style={{
                        background: "#ffffff",
                        borderRadius: "8px",
                        boxShadow: "0 1px 1px rgba(0, 0, 0, 0.1)",
                        borderRight: "none",
                    }}
                >
                    <RestNode nodeID={selectNodeID} />
                </Content>
            );
        }
    };

    // 处理菜单项选择
    const handleMenuSelect = (item: any) => {
        setSelect(item.key);
        // 更新URL参数
        if (item.key === "0") {
            // 特殊处理本机节点
            const searchParams = new URLSearchParams(window.location.search);
            searchParams.set("node_id", "0");
            const newUrl = `${window.location.pathname}?${searchParams.toString()}`;
            navigate(newUrl, { replace: true });
        } else if (item.key === "-1") {
            // 处理添加新节点的情况
            const searchParams = new URLSearchParams(window.location.search);
            searchParams.set("node_id", "-1");
            const newUrl = `${window.location.pathname}?${searchParams.toString()}`;
            navigate(newUrl, { replace: true });
        } else {
            // 处理其他节点
            const node = items.find((n: any) => n.key === item.key);
            if (node) {
                const searchParams = new URLSearchParams(
                    window.location.search,
                );
                searchParams.set("node_id", node.node_id);
                const newUrl = `${window.location.pathname}?${searchParams.toString()}`;
                navigate(newUrl, { replace: true });
                setSelectNodeID(node.node_id);
            }
        }
    };

    return (
        <Layout style={{ minHeight: "86vh" }}>
            <Sider
                style={{
                    background: "#ffffff",
                    borderRadius: "8px",
                    boxShadow: "0 1px 1px rgba(0, 0, 0, 0.1)",
                    borderRight: "none",
                }}
                width={300}
            >
                <div style={{ padding: "10px" }}>
                    <div
                        style={{
                            userSelect: "none",
                            minHeight: "60px",
                            display: "flex",
                            fontSize: "20px",
                            fontWeight: "bold",
                            color: "#333",
                            justifyContent: "center",
                            alignItems: "center",
                        }}
                    >
                        节点列表
                    </div>
                    <div
                        style={{
                            borderBottom: "1px solid #e9e9e9",
                        }}
                    />
                    <Menu
                        mode="inline"
                        selectedKeys={[select]}
                        defaultOpenKeys={["sub1"]}
                        style={{
                            borderRight: "none",
                            textAlign: "center",
                            padding: "12px 0",
                        }}
                        // @ts-ignore
                        items={items}
                        onSelect={handleMenuSelect}
                    />
                </div>
            </Sider>
            <div
                style={{
                    minWidth: "20px",
                }}
            />
            <MainContent />
        </Layout>
    );
};

export default Nodes;